// pages/todos/todos.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    input:'',
    leftCount:0,
    flag:true,
    todos :[
      { name: "JavaScript", completed: true },
      { name: "CSS", completed: false },
      { name:"HTML" , completed: true }
    ]
  },

  // 实例初始化完成后调用
  onLoad: function () {
    this.getLeftCount();
  },

  // 添加任务项 事件处理函数
  addTodoHandle:function(){
    if(!this.data.input) return;
    
    var todos = this.data.todos;
    var item = { name:this.data.input, completed:false };
    this.data.todos.push(item);
    this.setData({ todos : todos , input : ""});
    this.getLeftCount();
    
  },
  // 输入框中的数据改变时 触发该事件处理函数
  changedHandle:function(e){
    this.setData({ input: e.detail.value });
  },

  // 点击切换完成状态
  toggleTodoHandle:function(e){
    var item = this.data.todos[e.currentTarget.dataset.index];
    item.completed = !item.completed;
    var leftCount = 
    this.setData({ todos : this.data.todos });
    this.getLeftCount();

  },
  // 获取未完成的任务 个数
  getLeftCount:function(){
    
    var todos = this.data.todos;
    if (!todos.length) return 0;
    var list =todos.filter(item=>{
      return item.completed === false;
    })
    console.log(list.length)
    this.setData({ leftCount: list.length })
  },
  // 点击叉号 删除该任务项
  deleteItem: function(e){
    console.log(e.currentTarget.dataset.index)
    var index = e.currentTarget.dataset.index;
    var todos = this.data.todos;
    todos.splice(index, 1);
    this.setData({ todos: todos });
  },

  // 点击 Clear completed 清除所有已完成的
  clearCompleted:function(){
    var todos = this.data.todos;
    var list = todos.filter(item => {
      return item.completed === false;
    })
    this.setData({ todos: list })
  },

  toggleAll:function(){
    var flag = !this.data.flag;
    this.data.todos.forEach(item=>{
      item.completed = flag;
    });
    this.setData({ todos : this.data.todos , flag : flag})
  }


  
})